import {
 	enc,
 	dec
 } from "../../common/api/sec.js"
 import store from "../../store/index.js"
 import {
 	pars,
	removeProperty
 } from "./bytetostring.js"
 import sha256 from '@/common/api/sha256.js'
 import md5 from '@/common/api/md5.min.js'
export default {
	common: {
		// baseUrl:"http://192.168.0.114/ocean",		//本地
		baseUrl:"https://apidev.xuniuwang.com/ocean",		//测试环境
		// baseUrl:"https://openapi.zhihuixiaoqun.com",		//正式环境
		// baseUrl:'http://118.178.143.133/ocean',		//兼职测试接口
		// baseUrl:"http://118.178.143.133:1688/v2/api-docs",
		// baseUrl:"https://apidev.xuniuwang.com",
		header: {
			"productId": "ZHAO_ZHUN_JOB",
			"sVer": "2",
			"token":'',
			"did": '',
		},  
		data: {},
		method: "POST",
		responseType: "arraybuffer",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		//console.log('request(options)',options);
		if (!options) {
			options = {}
		}
		let firstData={
			url:options.url,
			data:options.data== undefined?{}:options.data
			
		}
		options.body={};
		this.common.header.did=uni.getStorageSync('did')
		if(uni.getStorageSync('token')){
			this.common.header.token=uni.getStorageSync('token')	
		}			
		options.url = this.common.baseUrl + options.url;
		if(options.header==undefined){		//如果option没有定义header
			options.header={}
			options.header=Object.assign(options.header,this.common.header)
		}else{
			options.header=Object.assign(options.header,this.common.header)
		}
		options.method = this.common.method;
		
		//如果是支付宝小程序则不加responseType属性,而是加上dataType属性
		//#ifndef MP-ALIPAY
		options.responseType = this.common.responseType;
		//#endif
		
		//#ifdef MP-ALIPAY
		options.dataType='arraybuffer';
		//#endif
		
		options.fail=function(err){
			console.log('fail:',err);
		}
		if(!options.data){
			options.data={}
		}
		let jsonStr = JSON.stringify(options.data);		//把options.data转为JSON格式
			
		let key=''
		let key2=''		
		if(store.state.key){
			key=store.state.key;
			key2=store.state.key2
		}
		let data = enc(jsonStr, key)	//对数据加密
		options.data = data.buffer;
		let value = md5(data);
		let obj = {},
			obj2 = {}
		let key1 = "data";
		obj[key1] = value;
		Object.assign(obj2,options.header, obj)
		removeProperty(obj2)		//删除对象中空属性
		let autograph = pars(obj2)	//将对象转换为’key=value&key=value‘形式
		console.log('autograph:',autograph);
		console.log('key:',key);
		console.log('key1:',key1);
		console.log('key2:',key2);
		let shaArr = sha256(autograph + key2).toString()
		let sign = "sign";
		let words = shaArr
		options.header[sign] = words
		return new Promise((resolve, reject) => {
			let _config = null		
			options.complete = (response) => {
				//console.log('response:',response);
				let statusCode = response.statusCode
				response.config = _config				
				let byteArray = new Uint8Array(response.data)				
				let data = dec(byteArray, key);		//解密
				let dataObj=JSON.parse(data)
				response.data=dataObj				
				response.firstData=firstData
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 统一的响应日志记录
				//_reslog(response)
				if (statusCode === 200) { //成功
					resolve(response)
				} else {
					reject(response)
				}
			}
					
			//this此时指向全局
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()
			//console.log('_config:',_config);
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			// 统一的请求日志记录
			//_reqlog(_config)

			// if (process.env.NODE_ENV === 'development') {
			// 	console.log("【" + _config.requestId + "】 地址：" + _config.url)
			// 	if (_config.data) {
			// 		console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
			// 	}
			// }
			// console.log(_config)
			
			
			//支付宝小程序
			//#ifdef MP-ALIPAY  
			console.log("支付宝小程序环境");
			uni.request(_config);
			//#endif 
			
			//微信小程序
			//#ifdef MP-WEIXIN
			console.log('微信小程序环境');
			uni.request(_config);
			//#endif
			
			//#ifdef H5
			console.log('H5环境');
			uni.request(_config)
			//#endif
			
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'  
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}


/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + req.requestId + "】 地址：" + req.url)
		if (req.data) {
			console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + res.config.requestId + "】 地址：" + res.config.url)
		if (res.config.data) {
			console.log("【" + res.config.requestId + "】 请求参数：" + JSON.stringify(res.config.data))
		}
		console.log("【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
	switch(_statusCode){
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}

